package com.jeesite.modules.yzw.service;

import com.jeesite.common.entity.Extend;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.modules.sys.dao.EmployeeOfficeDao;
import com.jeesite.modules.sys.entity.*;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.task.feedback.entity.DcSupTaskFeedback;
import com.jeesite.modules.yzw.dao.OtsDataDao;
import com.jeesite.modules.yzw.dao.OtsIflytekOrgDao;
import com.jeesite.modules.yzw.dao.OtsIflytekUserDao;
import com.jeesite.modules.yzw.entity.OtsIflytekOrg;
import com.jeesite.modules.yzw.entity.OtsIflytekOrgUser;
import com.jeesite.modules.yzw.entity.OtsIflytekUser;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OtsDataService {
    @Autowired
    private OtsDataDao otsDataDao;
    @Autowired
    private OtsIflytekOrgDao otsIflytekOrgDao;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeOfficeDao employeeOfficeDao;
    @Autowired
    private OtsIflytekUserDao otsIflytekUserDao;

    // 返回状态值
    private String code="";
    //计数器
    private  int count=0;

    /**
     * 新增或修改组织机构
     */
    @Transactional(rollbackFor = Exception.class)
    public String findListOrg() {
        try {
            //修改应执行错误导致的机构数据问题
            updateOtsIflytekOrg();
            //查询未同步的数据
            List<OtsIflytekOrg> list=otsDataDao.findListOrg();
            if (list.isEmpty()){
                return "success";
            }
          //新增或修改组织机构
            code=insertOrg(list);
        } catch (Exception e) {
            e.printStackTrace();
            code="error";
        }
        return code;
    }

    private String insertOrg(List<OtsIflytekOrg> list){
        try {
            count=0;
            for (OtsIflytekOrg org:list) {
                Office office = new Office();
                // 机构id
                if(org.getSyncstate()==0){
                    office.setViewCode(String.valueOf(org.getUrcorgid()));
                }else {
                    office.setOfficeCode(String.valueOf(org.getUrcorgid()));
                }
                Extend extend=new Extend();
                extend.setExtendS2(org.getId());
                office.setExtend(extend);
                // 机构父id
                if (org.getParentid() == null) {
                    office.setParentCode("0");
                }else if("-1".equals(org.getParentid())){
                    office.setParentCode("0");
                } else {
                    office.setParentCode(org.getWhdcpid());
                }
                // 机构简称
                office.setOfficeName(org.getJgjc());
                // 机构全称
                office.setFullName(org.getName());
                // 排序号
                office.setTreeSort(org.getTop());

                // 机构类型
                if("1".equals(org.getLeaderid())){
                    office.setOfficeType("0");
                }else {
                    office.setOfficeType("1");
                }

                // 机构状态，0正常
                if (org.getStatus()==1) {
                    office.setStatus("0");
                } else {
                    // 设置为停用
                    office.setStatus("2");
                }
                // 创建人
                office.setCreateBy("system");
                // 创建时间
                office.setCreateDate(new Date());
                officeService.save(office);
                //将已更新的数据状态变为已更新
                org.setSyncstate(3);
                otsIflytekOrgDao.modifyOtsIflytekOrgByid(org);
                count++;
                System.out.println("已更新" + count + "条数据");
            }
            System.out.println("总共更新" + count + "条数据");
            code = "success";
        } catch (Exception e) {
            e.printStackTrace();
            code="error";
        }finally {
            return code;
        }
    }

    /**
     * 新增或修改用户
     */
    @Transactional(rollbackFor = Exception.class)
    public String findListUser() {
        try {
            // 返回状态值
            String code="";
            //计数器
            int count=0;
            List<OtsIflytekUser> otsIflytekUserList=otsDataDao.findListUser();
            if(otsIflytekUserList.isEmpty()){
                findOmissionUserList();
                return "success";
            }
            // 循环插入
            for (OtsIflytekUser otsIflytekUser : otsIflytekUserList) {
                User user = new User();
                // 用户id
                if(otsIflytekUser.getSyncstate()==0){
                    user.setUserCode(IdGen.nextId());
                }else {
                    if(otsIflytekUser.getUrcid()==null){
                        user.setUserCode(IdGen.nextId());
                    }else {
                        user.setUserCode(String.valueOf(otsIflytekUser.getUrcid()));
                    }
                }
                // 用户登录id
                user.setLoginCode(otsIflytekUser.getMobile());
                // 用户名称
                user.setUserName(otsIflytekUser.getName());
                // 用户类型引用编号、名称
                user.setRefCode(user.getUserCode());
                user.setRefName(user.getUserName());
                // 手机号
                user.setMobile(otsIflytekUser.getMobile());
                // 性别
                user.setSex(otsIflytekUser.getSex());
                // 插入用户机构
                Employee employee = new Employee();
                // 用户编号
                employee.setEmpCode(user.getUserCode());
                // 用户名称
                employee.setEmpName(otsIflytekUser.getName());
                //扩展字段
                Extend extend=new Extend();
                //易政网主键
                extend.setExtendS2(otsIflytekUser.getId());
                extend.setExtendS1(otsIflytekUser.getTitle());
                user.setExtend(extend);
                List<OtsIflytekOrgUser> otsIflytekOrgUserList=otsDataDao.findListOrgUser(otsIflytekUser.getId());
                if(CollectionUtils.isNotEmpty(otsIflytekOrgUserList)){
                    for (int i = 0; i < otsIflytekOrgUserList.size(); i++) {
                        if(i==0){
                            OtsIflytekOrg org=new OtsIflytekOrg();
                            org.setId(otsIflytekOrgUserList.get(i).getDeptid());
                            org=getOtsIflytekOrgByid(org);
                            if(org!=null){
                                // 第一次进入，作为所属机构
                                Office office = new Office();
                                // 用户机构id
                                office.setOfficeCode(String.valueOf(org.getUrcorgid()));
                                // 用户机构名称
                                office.setOfficeName(org.getName());
                                employee.setOffice(office);
                                employee.setStatus("0");
                            }
                        }else {
                            // 第二次进入，作为附属机构
                            List<EmployeeOffice> employeeOfficeList = employee.getEmployeeOfficeList();
                            EmployeeOffice employeeOffice = new EmployeeOffice();
                            OtsIflytekOrg org=new OtsIflytekOrg();
                            org.setId(otsIflytekOrgUserList.get(i).getDeptid());
                            org=getOtsIflytekOrgByid(org);
                            if(org!=null){
                                employeeOffice.setOfficeCode(String.valueOf(org.getUrcorgid()));
                                employeeOffice.setOfficeName(org.getName());
                            }
                            employeeOfficeList.add(employeeOffice);
                        }
                    }
                }
                // 新增数据
                if(otsIflytekUser.getSyncstate()==0 || otsIflytekUser.getUrcid()==null){
                    // 用户类型
                    user.setUserType("employee");
                    // 用户状态
                    user.setStatus("0");
                    // 管理员类型
                    user.setMgrType("0");
                    // 用户密码，初始密码
                    user.setPassword("Lehand159");
                    // 创建人
                    user.setCreateBy("system");
                    user.setCreateDate(new Date());
                    //备注
                    user.setRemarks("易政网用户");
                    //新增用户
                    userService.insert(user);
                    //用户关联和用户对应组织
                    employeeService.insert(employee);
                    //重置密码
                    userService.updatePassword(user.getUserCode(), null);
                }
                //修改数据
                if(otsIflytekUser.getSyncstate()==1 && otsIflytekUser.getUrcid()!=null){
                    // 修改人
                    user.setUpdateBy("system");
                    user.setUpdateDate(new Date());
                    user.setMobile(null);
                    //修改用户信息
                    userService.update(user);
                    //修改用户关联和用户对应组织
                    employeeService.update(employee);
                }

                //将已更新的数据状态变为已更新
                otsIflytekUser.setSyncstate(3);
                otsIflytekUser.setUrcid(Long.valueOf(user.getUserCode()));
                otsIflytekUser.setUpdatetime(new Date());
                otsDataDao.updateUserSyncstate(otsIflytekUser);
                // 保存附属机构
                if (employee.getEmployeeOfficeList().size() > 0) {
                    EmployeeOffice employeeOfficeWhere = new EmployeeOffice();
                    employeeOfficeWhere.setEmpCode(employee.getEmpCode());
                    employeeOfficeDao.deleteByEntity(employeeOfficeWhere);
                    employee.getEmployeeOfficeList().forEach(employeeOffice -> {
                        employeeOffice.setId(IdGen.nextId());
                        employeeOffice.setEmpCode(employee.getEmpCode());
                    });
                    employeeOfficeDao.insertBatch(employee.getEmployeeOfficeList());
                }
                //将已更新的数据状态变为已更新
                for (OtsIflytekOrgUser otsIflytekOrgUser:otsIflytekOrgUserList) {
                    otsIflytekOrgUser.setSyncstate(3);
                    otsDataDao.updateOrgUserSyncstate(otsIflytekOrgUser);
                }
                //修改
                count++;
                System.out.println("已更新到=============》》》" + count);
            }
            System.out.println("总共更新" + count + "条数据");
            code = "success";
        } catch (Exception e) {
            e.printStackTrace();
            code = "error";
        }finally {
            return code;
        }
    }

    /**
     * 老系统把用户数据删除   保持与易政网用户相同
     */
    private void findOmissionUserList() {
        try {
            // 返回状态值
            String code="";
            //计数器
            int count=0;
            List<OtsIflytekUser> otsIflytekUserList=otsDataDao.findOmissionUserList();
            if(otsIflytekUserList.isEmpty()){
                return;
            }
            // 循环插入
            for (OtsIflytekUser otsIflytekUser : otsIflytekUserList) {
                User user = new User();
                // 用户id
                if(otsIflytekUser.getUrcid()!=null){
                    user.setUserCode(String.valueOf(otsIflytekUser.getUrcid()));
                }else {
                    user.setUserCode(IdGen.nextId());
                }
                // 用户登录id
                user.setLoginCode(otsIflytekUser.getMobile());
                // 用户名称
                user.setUserName(otsIflytekUser.getName());
                // 用户类型引用编号、名称
                user.setRefCode(user.getUserCode());
                user.setRefName(user.getUserName());
                // 手机号
                user.setMobile(otsIflytekUser.getMobile());
                // 性别
                user.setSex(otsIflytekUser.getSex());
                // 插入用户机构
                Employee employee = new Employee();
                // 用户编号
                employee.setEmpCode(user.getUserCode());
                // 用户名称
                employee.setEmpName(otsIflytekUser.getName());
                //扩展字段
                Extend extend=new Extend();
                //易政网主键
                extend.setExtendS2(otsIflytekUser.getId());
                extend.setExtendS1(otsIflytekUser.getTitle());
                user.setExtend(extend);
                // 用户类型
                user.setUserType("employee");
                // 用户状态
                user.setStatus("0");
                // 管理员类型
                user.setMgrType("0");
                // 用户密码，初始密码
                user.setPassword("Lehand159");
                // 创建人
                user.setCreateBy("system");
                user.setCreateDate(new Date());
                //备注
                user.setRemarks("易政网用户");

                List<OtsIflytekOrgUser> otsIflytekOrgUserList=otsDataDao.findListOrgUser(otsIflytekUser.getId());
                if(CollectionUtils.isNotEmpty(otsIflytekOrgUserList)){
                    for (int i = 0; i < otsIflytekOrgUserList.size(); i++) {
                        if(i==0){
                            OtsIflytekOrg org=new OtsIflytekOrg();
                            org.setId(otsIflytekOrgUserList.get(i).getDeptid());
                            org=getOtsIflytekOrgByid(org);
                            if(org!=null){
                                // 第一次进入，作为所属机构
                                Office office = new Office();
                                // 用户机构id
                                office.setOfficeCode(String.valueOf(org.getUrcorgid()));
                                // 用户机构名称
                                office.setOfficeName(org.getName());
                                employee.setOffice(office);
                                employee.setStatus("0");
                            }
                        }else {
                            // 第二次进入，作为附属机构
                            List<EmployeeOffice> employeeOfficeList = employee.getEmployeeOfficeList();
                            EmployeeOffice employeeOffice = new EmployeeOffice();
                            OtsIflytekOrg org=new OtsIflytekOrg();
                            org.setId(otsIflytekOrgUserList.get(i).getDeptid());
                            org=getOtsIflytekOrgByid(org);
                            if(org!=null){
                                employeeOffice.setOfficeCode(String.valueOf(org.getUrcorgid()));
                                employeeOffice.setOfficeName(org.getName());
                            }
                            employeeOfficeList.add(employeeOffice);
                        }
                    }
                }
                //新增用户
                userService.insert(user);
                //用户关联和用户对应组织
                employeeService.insert(employee);
                //重置密码
                userService.updatePassword(user.getUserCode(), null);

                // 保存附属机构
                if (employee.getEmployeeOfficeList().size() > 0) {
                    EmployeeOffice employeeOfficeWhere = new EmployeeOffice();
                    employeeOfficeWhere.setEmpCode(employee.getEmpCode());
                    employeeOfficeDao.deleteByEntity(employeeOfficeWhere);
                    employee.getEmployeeOfficeList().forEach(employeeOffice -> {
                        employeeOffice.setId(IdGen.nextId());
                        employeeOffice.setEmpCode(employee.getEmpCode());
                    });
                    employeeOfficeDao.insertBatch(employee.getEmployeeOfficeList());

                    //将已更新的数据状态变为已更新
                    for (OtsIflytekOrgUser otsIflytekOrgUser:otsIflytekOrgUserList) {
                        otsIflytekOrgUser.setSyncstate(3);
                        otsDataDao.updateOrgUserSyncstate(otsIflytekOrgUser);
                    }
                }
                //修改
                count++;
                System.out.println("已更新到=============》》》" + count);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

    }


    /**
     * 根据机构id查询机构
     * @param
     * @return
     */
    private OtsIflytekOrg getOtsIflytekOrgByid(OtsIflytekOrg org){
        org=otsDataDao.getOtsIflytekOrgByid(org);
        return org;
    }
    /**
     * 剔除status为2（无效）的组织
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrg() {
        try {
            //查询未同步的数据
            OtsIflytekOrg otsIflytekOrg=new OtsIflytekOrg();
            otsIflytekOrg.setStatus(2);
            List<OtsIflytekOrg> list=otsDataDao.findListOrgByStatus(otsIflytekOrg);
            if(!list.isEmpty()){
                for (OtsIflytekOrg org:list) {
                    Office office=new Office();
                    office.setOfficeCode(String.valueOf(org.getUrcorgid()));
                    officeService.delete(office);
                }
            }

            //剔除全量同步与易政网不同的，系统已存在的组织
            List<Office> officeList=otsDataDao.findOfficeList();
            if(!officeList.isEmpty()){
                for (Office office:officeList) {
                    officeService.delete(office);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 剔除status为2（无效）的用户
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser() {
        try {
            //查询未同步的数据
            OtsIflytekUser otsIflytekUser=new OtsIflytekUser();
            otsIflytekUser.setStatus(2);
            List<OtsIflytekUser> list=otsDataDao.findListUserByStatus(otsIflytekUser);
            for (OtsIflytekUser user:list) {
                EmpUser empUser=new EmpUser();
                empUser.setUserCode(user.getUcuserid());
                empUserService.delete(empUser);
            }
            //查询不存在易政网用户中间表的用户
            List<User> userList=otsDataDao.findDeleteUserList();
            for (User user:userList) {
                if(User.isSuperAdmin(user.getUserCode())){
                    continue;
                }
                EmpUser empUser=new EmpUser();
                empUser.setUserCode(user.getUserCode());
                empUserService.delete(empUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 组织用户关系入库
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public void findOrgUser() {
        try {
            int count=0;
            //查询未同步的机构用户关系
            List<OtsIflytekOrgUser> otsIflytekOrgUserList=otsDataDao.findOrgUser();
            if(otsIflytekOrgUserList.isEmpty()){
                return;
            }
            /**
             * 不考虑用户之前的组织关系，直接将获得的新的组织关系作为子机构保存。这样肯定是有问题，待后续优化
             */
            for (OtsIflytekOrgUser otsIflytekOrgUser:otsIflytekOrgUserList) {
                //根据id获取用户的urcid
                OtsIflytekUser otsIflytekUser=new OtsIflytekUser();
                otsIflytekUser.setCompid(1L);
                otsIflytekUser.setUcuserid(otsIflytekOrgUser.getUserid());
                otsIflytekUser=otsIflytekUserDao.getOtsIflytekUser(otsIflytekUser);
                if(otsIflytekUser==null||otsIflytekUser.getUrcid()==null){
                    continue;
                }
                OtsIflytekOrg otsIflytekOrg=new OtsIflytekOrg();
                otsIflytekOrg.setId(otsIflytekOrgUser.getDeptid());
                //根据id获取机构的urcorgid
                otsIflytekOrg=otsDataDao.getOtsIflytekOrgByid(otsIflytekOrg);
                if(otsIflytekOrg==null||otsIflytekOrg.getUrcorgid()==null){
                    continue;
                }
                //完善用户机构信息，新增
                EmployeeOffice employeeOffice=new EmployeeOffice();
                employeeOffice.setId(IdGen.nextId());
                employeeOffice.setEmpCode(String.valueOf(otsIflytekUser.getUrcid()));
                employeeOffice.setOfficeCode(String.valueOf(otsIflytekOrg.getUrcorgid()));
                employeeOffice.setOfficeName(otsIflytekOrg.getName());
                employeeOfficeDao.insert(employeeOffice);
                count++;
            }
            System.out.println("修改机构用户关系"+count+"条");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过当前系统的用户id，获取其在易政网中的id
     * @param userCode
     * @return
     */
    String getIflyId(String userCode){
        return otsDataDao.getIflyId(userCode);
    }

    public void updateActionAndFeedback() {
        //查询feedback表中feedback_progress是3或者4的数据
        List<DcSupTaskFeedback> list = otsDataDao.getFeedback();
        for (int i = 0; i < list.size(); i++) {
            //循环修改大于feedback_end_time的feedback_status为11无需反馈
            otsDataDao.updateFeedback(list.get(i).getActionId(),list.get(i).getFeedbackEndTime());
            //循环修改action的task_status为4已结束
            otsDataDao.updateAction(list.get(i).getActionId());
        }

        //查询6-20到7-20的feedback表中已反馈的且反馈截止时间大于反馈时间
        List<DcSupTaskFeedback> list2 = otsDataDao.getFeedback2();
        //修改反馈时间为反馈截止时间的前一天
        for (int i = 0; i < list2.size(); i++) {
            otsDataDao.updateFeedback2(list2.get(i).getId(),DateUtils.addDays(list2.get(i).getFeedbackEndTime(),-1));
        }
    }

    private void updateOtsIflytekOrg() {
        List<OtsIflytekOrg> list=otsDataDao.findOtsIflytekOrg();
        for (OtsIflytekOrg org:list) {
            org.setSyncstate(0);
            otsIflytekOrgDao.modifyOtsIflytekOrgByid(org);
        }
    }
}
